import asyncio

import aiohttp
import requests

'''
请求实体
'''


def handle_response(result):
    response_status = result.get("status")
    if response_status:
        if response_status == 400:
            raise Exception("请求的参数不正确")
        if response_status == 401:
            raise Exception("用户信息不正确")
        if response_status == 403:
            raise Exception("缺少对应功能的权限")
        if response_status == 404:
            raise Exception("账号密码错误，或未开放功能权限")
        if response_status == 500:
            raise Exception("语雀服务器异常")


class YqRequest:
    def __init__(self, namespace, Token):
        self.base_url = "https://www.yuque.com/api/v2"
        self.namespace = namespace
        self.Token = Token
        self.headers = {
            "Content-Type": "application/json",
            "User-Agent": self.namespace,
            "X-Auth-Token": self.Token
        }
        # 并发限制
        self.semaphore = asyncio.Semaphore(200)
        # 请求文章内容超时时间
        self.time_out = aiohttp.ClientTimeout(total=3)
        # 请求图片超时时间
        self.pic_timeout = aiohttp.ClientTimeout(total=5)

    # 发送get请求
    def do_get(self, url):
        r = requests.get(self.base_url + url, headers=self.headers)
        result = r.json()
        handle_response(result)
        return result

    # 异步请求
    async def do_async_get(self, url):
        async with self.semaphore:
            async with aiohttp.ClientSession() as session:
                async with session.get(self.base_url + url, headers=self.headers, timeout=self.time_out) as resp:
                    result = await resp.json()
                    handle_response(result)
                    return result

    # test get_toc
    def get_toc(self):
        r = requests.get(self.base_url + "/repos/xiaopihu/toc", headers=self.headers)
        # r = requests.get(self.base_url + "/users/xiaopihu/repos", headers=self.headers)
        result = r.json()
        print(result)


if __name__ == "__main__":
    yq = YqRequest("xxx", "xxxx")
    yq.get_toc()